package me.zhengjie.modules.fund.reptile.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.fund.domain.StockNetValue;
import me.zhengjie.modules.fund.reptile.StockCrawler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 网易
 */
@Slf4j
@Component
public class StockNetEasyCrawler implements StockCrawler {

    public static final String GET_STOCK_DETAIL_URL = "https://quotes.money.163.com/trade/lsjysj_%s.html";

    @Override
    public List<StockNetValue> getLastedNetValues(String code) throws IOException {
        String url = String.format(GET_STOCK_DETAIL_URL, code);

        Document document = Jsoup.connect(url).get();

        String name = document.select("div.stock_info").select("h1.name > a").text();

        Elements elements = document.select("table.table_bg001");

        Elements trs = elements.select("tbody > tr");

        List<StockNetValue> netValues = new ArrayList<>();
        for (Element tr : trs) {
            StockNetValue stockNetValue = new StockNetValue();

            Elements tds = tr.getElementsByTag("td");

            stockNetValue.setCode(code);
            stockNetValue.setName(name);

            stockNetValue.setDate(DateUtil.parse(tds.get(0).text(), "yyyy-MM-dd"));
            stockNetValue.setStartValue(new BigDecimal(tds.get(1).text()));
            stockNetValue.setMaxValue(new BigDecimal(tds.get(2).text()));
            stockNetValue.setMinValue(new BigDecimal(tds.get(3).text()));
            stockNetValue.setNetValue(new BigDecimal(tds.get(4).text()));
            stockNetValue.setProfitAmount(new BigDecimal(tds.get(5).text()));
            stockNetValue.setProfitRate(new BigDecimal(tds.get(6).text()).divide(BigDecimal.valueOf(100)));
            stockNetValue.setConfirmNo(Integer.valueOf(tds.get(7).text().replace(",", "")));
            stockNetValue.setConfirmAmount(new BigDecimal(tds.get(8).text().replace(",", "")));

            netValues.add(stockNetValue);
        }

        log.info("{}", JSON.toJSONString(netValues));
        return netValues;
    }
}
